﻿@model ShoppingCartModel
@using System.Text
@using Nop.Core.Domain.Catalog
@using Nop.Core.Domain.Media
@using Nop.Services.Media
@inject IDownloadService downloadService
@inject CatalogSettings catalogSettings

@if (Model.CheckoutAttributes.Count > 0)
{
    var attributeChangeScriptsBuilder = new StringBuilder();
    <div class="checkout-attributes">
        <dl>
            @foreach (var attribute in Model.CheckoutAttributes)
            {
                var controlId = $"checkout_attribute_{attribute.Id}";
                var textPrompt = !string.IsNullOrEmpty(attribute.TextPrompt) ? attribute.TextPrompt : attribute.Name;
                <dt id="@($"checkout_attribute_label_{attribute.Id}")">
                    <label class="text-prompt">
                        @textPrompt
                    </label>
                    @if (attribute.IsRequired)
                    {
                        <span class="required">*</span>
                    }
                </dt>
                <dd id="@($"checkout_attribute_input_{attribute.Id}")">
                    @switch (attribute.AttributeControlType)
                    {
                        case AttributeControlType.DropdownList:
                            {
                        <select name="@(controlId)" id="@(controlId)">
                            @if (!attribute.IsRequired)
                            {
                                <option value="0">---</option>
                            }
                            @foreach (var attributeValue in attribute.Values)
                            {
                                var attributeName = string.IsNullOrEmpty(attributeValue.PriceAdjustment) ?
                                    attributeValue.Name :
                                    T("ShoppingCart.CheckoutAttributes.PriceAdjustment", attributeValue.Name, attributeValue.PriceAdjustment).Text; 
                                <option selected="@attributeValue.IsPreSelected" value="@attributeValue.Id">@attributeName</option>
                            }
                        </select>
                            attributeChangeScriptsBuilder.AppendFormat("$('#{0}').on('change', function(){{checkoutAttributeChange();}});\n", controlId);
                            }
                            break;
                        case AttributeControlType.RadioList:
                            {
                        <ul class="option-list">
                            @foreach (var attributeValue in attribute.Values)
                            {
                                var attributeName = string.IsNullOrEmpty(attributeValue.PriceAdjustment) ?
                                    attributeValue.Name :
                                    T("ShoppingCart.CheckoutAttributes.PriceAdjustment", attributeValue.Name, attributeValue.PriceAdjustment).Text; 
                                <li>
                                    <input id="@(controlId)_@(attributeValue.Id)" type="radio" name="@(controlId)" value="@attributeValue.Id" checked="@attributeValue.IsPreSelected" />
                                    <label for="@(controlId)_@(attributeValue.Id)">@attributeName</label>
                                </li>
                                attributeChangeScriptsBuilder.AppendFormat("$('#{0}_{1}').on('click', function(){{checkoutAttributeChange();}});\n", controlId, attributeValue.Id);
                            }
                        </ul>
                            }
                            break;
                        case AttributeControlType.Checkboxes:
                        case AttributeControlType.ReadonlyCheckboxes:
                            {
                        <ul class="option-list">
                            @foreach (var attributeValue in attribute.Values)
                            {
                                var attributeName = string.IsNullOrEmpty(attributeValue.PriceAdjustment) ?
                                    attributeValue.Name :
                                    T("ShoppingCart.CheckoutAttributes.PriceAdjustment", attributeValue.Name, attributeValue.PriceAdjustment).Text; 
                                <li>
                                    <input id="@(controlId)_@(attributeValue.Id)" type="checkbox" name="@(controlId)" value="@attributeValue.Id" checked="@attributeValue.IsPreSelected" @(attribute.AttributeControlType == AttributeControlType.ReadonlyCheckboxes ? Html.Raw(" disabled=\"disabled\"") : null) />
                                    <label for="@(controlId)_@(attributeValue.Id)">@attributeName</label>
                                </li>
                                attributeChangeScriptsBuilder.AppendFormat("$('#{0}_{1}').on('click', function(){{checkoutAttributeChange();}});\n", controlId, attributeValue.Id);
                            }
                        </ul>
                            }
                            break;
                        case AttributeControlType.TextBox:
                            {
                                <input name="@(controlId)" type="text" class="textbox" id="@(controlId)" value="@(attribute.DefaultValue)" />
                            }
                            break;
                        case AttributeControlType.MultilineTextbox:
                            {
                                <textarea id="@(controlId)" name="@(controlId)">@(attribute.DefaultValue)</textarea>
                            }
                            break;
                        case AttributeControlType.Datepicker:
                            {
                                <nop-date-picker 
                                    asp-day-name="@(controlId + "_day")" 
                                    asp-month-name="@(controlId + "_month")" 
                                    asp-year-name="@(controlId + "_year")"
                                    asp-begin-year="@(DateTime.Now.Year)"
                                    asp-end-year="@(DateTime.Now.Year + catalogSettings.CountDisplayedYearsDatePicker)"
                                    asp-selected-day="@(attribute.SelectedDay)"
                                    asp-selected-month="@(attribute.SelectedMonth)"
                                    asp-selected-year="@(attribute.SelectedYear)"
                                />
                            }
                            break;
                        case AttributeControlType.FileUpload:
                            {
                                Download download = null;
                                if (!string.IsNullOrEmpty(attribute.DefaultValue))
                                {
                                    download = downloadService.GetDownloadByGuid(new Guid(attribute.DefaultValue));
                                }

                                //register CSS and JS
                                Html.AddCssFileParts("~/lib/fineuploader/fine-uploader.min.css");
                                Html.AddScriptParts(ResourceLocation.Footer, "~/lib/fineuploader/jquery.fine-uploader.min.js");

                                //ex. ['jpg', 'jpeg', 'png', 'gif'] or []
                                var allowedFileExtensions = string.Join(", ", attribute.AllowedFileExtensions.Select(x => "'" + x.Trim() + "'").ToList());

                                if (download != null)
                                {
                                    <input id="@(controlId)" name="@(controlId)" type="hidden" value="@download.DownloadGuid" />
                                }
                                else
                                {
                                    <input id="@(controlId)" name="@(controlId)" type="hidden" />
                                }
                       
                                @*fine uploader container*@
                                <div id="@(controlId)uploader"></div>
                                @*fine uploader template (keep it synchronized to \Content\fineuploader\templates\default.html)*@
                                <script type="text/template" asp-location="Footer" id="@(controlId)-qq-template">
                                    <div class="qq-uploader-selector qq-uploader">
                                        <div class="qq-upload-drop-area-selector qq-upload-drop-area" qq-hide-dropzone>
                                            <span>@T("Common.FileUploader.DropFiles")</span>
                                        </div>
                                        <div class="qq-upload-button-selector qq-upload-button">
                                            <div>@T("Common.FileUploader.Upload")</div>
                                        </div>
                                        <span class="qq-drop-processing-selector qq-drop-processing">
                                            <span>@T("Common.FileUploader.Processing")</span>
                                            <span class="qq-drop-processing-spinner-selector qq-drop-processing-spinner"></span>
                                        </span>
                                        <ul class="qq-upload-list-selector qq-upload-list">
                                            <li>
                                                <div class="qq-progress-bar-container-selector">
                                                    <div class="qq-progress-bar-selector qq-progress-bar"></div>
                                                </div>
                                                <span class="qq-upload-spinner-selector qq-upload-spinner"></span>
                                                <span class="qq-edit-filename-icon-selector qq-edit-filename-icon"></span>
                                                <span class="qq-upload-file-selector qq-upload-file"></span>
                                                <input class="qq-edit-filename-selector qq-edit-filename" tabindex="0" type="text">
                                                <span class="qq-upload-size-selector qq-upload-size"></span>
                                                <a class="qq-upload-cancel-selector qq-upload-cancel" href="#">@T("Common.FileUploader.Cancel")</a>
                                                <a class="qq-upload-retry-selector qq-upload-retry" href="#">@T("Common.FileUploader.Retry")</a>
                                                <a class="qq-upload-delete-selector qq-upload-delete" href="#">@T("Common.FileUploader.Delete")</a>
                                                <span class="qq-upload-status-text-selector qq-upload-status-text"></span>
                                            </li>
                                        </ul>
                                    </div>
                                </script>
                                <script asp-location="Footer">
                                    $(document).ready(function() {
                                        $("#@(controlId)uploader").fineUploader({
                                            request: {
                                                endpoint: '@(Url.RouteUrl("UploadFileCheckoutAttribute", new {attributeId = attribute.Id}))'
                                            },
                                            template: "@(controlId)-qq-template",
                                            multiple: false,
                                            validation: {
                                                allowedExtensions: [@Html.Raw(allowedFileExtensions)]
                                            }
                                        }).on("complete", function(event, id, name, responseJSON, xhr) {
                                            $("#@(controlId)").val(responseJSON.downloadGuid);
                                            if (responseJSON.success) {
                                                $("#@(controlId + "downloadurl")").html("<a href='" + responseJSON.downloadUrl + "'>@T("Common.FileUploader.DownloadUploadedFile")</a>");
                                                $("#@(controlId + "remove")").show();
                                            }
                                            if (responseJSON.message) {
                                                alert(responseJSON.message);
                                            }
                                        });

                                        $("#@(controlId + "remove")").on("click", function(e) {
                                            $("#@(controlId + "downloadurl")").html("");
                                            $("#@(controlId)").val('');
                                            $(this).hide();
                                        });
                                    });
                                </script>
                                <div id="@(controlId + "downloadurl")">
                                    @if (download != null)
                                    {
                                        <a href="@(Url.Action("GetFileUpload", "Download", new { downloadId = download.DownloadGuid }))" class="download-uploaded-file">@T("Common.FileUploader.DownloadUploadedFile")</a>
                                    }
                                </div>
                                <div>
                                    @if (download != null)
                                    {
                                        <a id="@(controlId + "remove")" class="remove-download-button">@T("Common.FileUploader.RemoveDownload")</a>
                                    }
                                    else
                                    {
                                        <a id="@(controlId + "remove")" class="remove-download-buttonn" style="display:none;">@T("Common.FileUploader.RemoveDownload")</a>
                                    }
                                </div>
                            }
                            break;
                        case AttributeControlType.ColorSquares:
                            {
                                <ul class="option-list attribute-squares color-squares" id="color-squares-@(attribute.Id)">
                                    @foreach (var attributeValue in attribute.Values)
                                    {
                                        var attributeName = string.IsNullOrEmpty(attributeValue.PriceAdjustment) ?
                                            attributeValue.Name :
                                            T("ShoppingCart.CheckoutAttributes.PriceAdjustment", attributeValue.Name, attributeValue.PriceAdjustment).Text; 
                                        <li @(attributeValue.IsPreSelected ? @Html.Raw(" class=\"selected-value\"") : null)>
                                            <label for="@(controlId)_@(attributeValue.Id)">
                                                <span class="attribute-square-container" title="@attributeName">
                                                    <span class="attribute-square" style="background-color:@(attributeValue.ColorSquaresRgb);">&nbsp;</span>
                                                </span>
                                                <input id="@(controlId)_@(attributeValue.Id)" type="radio" name="@(controlId)" value="@attributeValue.Id" checked="@attributeValue.IsPreSelected" />
                                                @*uncomment below to display attribute value name*@
                                                @*<span class="name">@attributeName</span>*@
                                            </label>
                                        </li>
                                        attributeChangeScriptsBuilder.AppendFormat("$('#{0}_{1}').on('click', function(){{checkoutAttributeChange();}});\n", controlId, attributeValue.Id);
                                    }
                                </ul>
                                <script asp-location="Footer">
                                    $(document).ready(function() {
                                        $('.checkout-attributes #color-squares-@(attribute.Id)').on('click', 'input', function (event) {
                                            $('.checkout-attributes #color-squares-@(attribute.Id)').find('li').removeClass('selected-value');
                                            $(this).closest('li').addClass('selected-value');
                                        });
                                   });
                                </script>
                            }
                            break;
                        case AttributeControlType.ImageSquares:
                            {
                                //not support attribute type
                            }
                            break;
                    }
                </dd>
            }
        </dl>
    </div>
    <script asp-location="Footer">
        $(document).ready(function() {
            checkoutAttributeChange();
            @Html.Raw(attributeChangeScriptsBuilder.ToString())
        });

        function checkoutAttributeChange() {
            $.ajax({
                cache: false,
                url: "@Html.Raw(Url.Action("checkoutattributechange", "shoppingcart", new { isEditable = Model.IsEditable }))",
                data: $('#shopping-cart-form').serialize(),
                type: "POST",
                success: function (data, textStatus, jqXHR) {
                    if (data.ordetotalssectionhtml) {
                        $('.total-info').replaceWith(data.ordetotalssectionhtml);
                    }
                    if (data.selectedcheckoutattributesssectionhtml) {
                        $('.selected-checkout-attributes').replaceWith(data.selectedcheckoutattributesssectionhtml);
                    }
                    if (data.enabledattributeids) {
                        for (var i = 0; i < data.enabledattributeids.length; i++) {
                            $('#checkout_attribute_label_' + data.enabledattributeids[i]).show();
                            $('#checkout_attribute_input_' + data.enabledattributeids[i]).show();
                        }
                    }
                    if (data.disabledattributeids) {
                        for (var i = 0; i < data.disabledattributeids.length; i++) {
                            $('#checkout_attribute_label_' + data.disabledattributeids[i]).hide();
                            $('#checkout_attribute_input_' + data.disabledattributeids[i]).hide();
                        }
                    }
                    $(document).trigger({ type: "checkout_attributes_changed", changedData: data });
                }
            });
        }
    </script>
}